import React, {useEffect, useState} from "react";
import type {TableColumnsType} from 'antd';
import {Affix, Button, Flex, FloatButton, Modal, Table, Switch} from 'antd';
import style from "@/pages/users/index.css";
import {connect} from "umi";

import ClassModal from "@/pages/class/components/ClassModal";
import AssignModal from "@/pages/class/components/AssignModal";

interface DataType {
  key: React.Key;
  id: string;
  className: string;
  teacherName: string;
  teacherId: string;
  classCreateTime: number;
}

interface ExpandedDataType {
  key: React.Key;
  stuNo: string;
  gender: string;
  name: string;
  phone: string;
  email: string;
  address: string;
  description: string;
  stuCreateTime: string;
}

const Class = (props) => {

  const {classes: {classList, userRoleId, teacherList, classStuIds, allStuList}, dispatch} = props
  const [visible, setVisible] = useState(false)
  const [assignVisible, setAssignVisible] = useState(false)
  const [record, setRecord] = useState(undefined)
  const [expandedRows, setExpandedRows] = React.useState([]);
  const [allExpand, setAllExpand] = useState(false);

  useEffect(() => {
    dispatch({
      type: 'classes/findClassInfo',
    })
  }, [])

  const { confirm } = Modal;

  const removeStu = (record) => {
    confirm({
      content: '你确定要将这个用户移出此班级吗？',
      onOk() {
        dispatch({
          type: 'classes/removeStu',
          payload: record.stuNo,
        }).then(() => {
          dispatch({
            type: 'classes/findClassInfo',
          })
        })
      },
      onCancel() {},
      okText: '确定',
      cancelText: '取消',
      centered: true,
    });
  }

  const expandedRowRender = (record) => {
    const columns: TableColumnsType<ExpandedDataType> = [
      {title: '学号', dataIndex: 'stuNo', key: 'stuNo'},
      {title: '姓名', dataIndex: 'name', key: 'name'},
      {title: '性别', dataIndex: 'gender', key: 'gender',},
      {title: '电话', dataIndex: 'phone', key: 'phone'},
      {title: '邮箱', dataIndex: 'email', key: 'email',},
      {title: '地址', dataIndex: 'address', key: 'address',},
      {title: '描述', dataIndex: 'description', key: 'description',},
      {title: '加入时间', dataIndex: 'stuCreateTime', key: 'stuCreateTime',},
      userRoleId === 42 ? {title: '操作', key: 'stuCreateTime', render: (item) => (
          <div>
            <Button type="primary" danger size="small" onClick={() => removeStu(item)}>移除</Button>
          </div>
        )} : {}
    ];

    const data = [];
    classList.map(item => {
      if(item.children) {
        item.children.map(stu => {
          if(record.id === stu.classId) {
            data.push({
              key: stu.stuNo,
              stuNo: stu.stuNo,
              gender: stu.gender,
              name: stu.name,
              phone: stu.phone,
              email: stu.email,
              address: stu.address,
              description: stu.description,
              stuCreateTime: stu.stuCreateTime
            });
          }
        })
      }
    })

    return <Table rowKey={record => record.stuNo} columns={columns} dataSource={data} pagination={false}/>;
  };

  const deleteClass = (record) => {
    confirm({
      content: '你确定要删除这个班级吗？',
      onOk() {
        dispatch({
          type: 'classes/deleteClass',
          payload: record.id,
        }).then(() => {
          dispatch({
            type: 'classes/findClassInfo',
          })
        })
      },
      onCancel() {},
      okText: '确定',
      cancelText: '取消',
      centered: true,
    });
  }

  const handleChange = (record) => {
    setRecord(record)
    setVisible(true)
  }

  const handleAdd = () => {
    setVisible(true)
    setRecord(undefined)
  }

  const onFinish = (values) => {
    let id = 0
    if(record) {
      id = record.id
    }
    if(id) {
      dispatch({
        type: 'classes/updateSysClass',
        payload: {
          id: record.id,
          className: values.className,
          teacherId: values.teacherId,
        },
      }).then(() => {
        setVisible(false)
        dispatch({
          type: 'classes/findClassInfo',
        })
      })
    } else {
      dispatch({
        type: 'classes/saveSysClass',
        payload: {
          className: values.className,
          teacherId: values.teacherId,
        },
      }).then(() => {
        setVisible(false)
        dispatch({
          type: 'classes/findClassInfo',
        })
      })
    }
  }

  const columns: TableColumnsType<DataType> = [
    {title: '班级名', dataIndex: 'className', key: 'className'},
    {title: '教师名', dataIndex: 'teacherName', key: 'teacherName'},
    {title: '创建时间', dataIndex: 'classCreateTime', key: 'classCreateTime'},
    {title: '操作', hidden: userRoleId !== 42, render: (record) => (
        <div>
          <Flex gap="small">
            <Button type="primary" size="small" onClick={() => handleChange(record)}>修改</Button>
            <Button type="primary" size="small" danger onClick={() => deleteClass(record)}>删除</Button>
            <Button style={{color: "white", background: "#e3a33f"}} size="small" onClick={() => assignStu(record)}>分配学生</Button>
          </Flex>
        </div>
      )},
  ];

  const assignStu = async (record) => {
    setRecord(record)
    await dispatch({
      type: 'classes/getClassStu',
      payload: {classId: record.id},
    })
  }

  useEffect(() => {
    if(classStuIds !== undefined) {
      setAssignVisible(true)
    }
  }, [classStuIds])

  const data: DataType[] = [];
  classList.map(item => {
    data.push({
      key: item.id,
      id: item.id,
      className: item.className,
      teacherName: item.teacherName,
      teacherId: item.teacherId,
      classCreateTime: item.classCreateTime,
    });
  })

  const closeHandler = () => {
    setVisible(false)
  }

  const closeAssign = () => {
    setAssignVisible(false)
    dispatch({
      type: 'classes/initClassStuIds',
    })
  }

  const confirmAssign = (values) => {
    dispatch({
      type: 'classes/assignStu',
      payload: {
        classId: record.id,
        stuId: values.stuIds
      }
    }).then(() => {
      setAssignVisible(false)
      dispatch({
        type: 'classes/findClassInfo',
      })
    })
  }

  const handleExpand = (expanded, record) => {
    if(expanded) {
      setExpandedRows(preRows => [...preRows, record.id])
    } else {
      setExpandedRows(prevRows => prevRows.filter(row => row !== record.id))
    }
  }

  const handleAllExpand = (checked: boolean) => {
    if(checked) {
      setExpandedRows(data.map(item => {
        return item.id
      }))
    } else {
      setExpandedRows([])
    }
  }

  return (
    <div>
      {/*<div style={{textAlign: "center",fontSize: "35px" , marginBottom: "10px", height: "75px", width: "100%", background: "#fff", padding: "10px", border: "1px solid #ebeef5", borderRadius: "3px"}}>
        课程管理界面
      </div>*/}
      <div hidden={userRoleId !== 42} style={{margin: "10px 0", width: "100%", background: "#fff", padding: "10px", border: "1px solid #ebeef5", borderRadius: "3px"}}>
        <Button className={style.add} onClick={handleAdd}>添加</Button>
      </div>
      <div style={{margin: "10px 0", width: "100%", background: "#fff", padding: "10px", border: "1px solid #ebeef5", borderRadius: "3px"}}>
        <Affix offsetTop={20}>
          <Switch checkedChildren="全部展开" unCheckedChildren="全部收起"  onChange={handleAllExpand}/>
        </Affix>
      </div>
      <Table
        rowKey={record => record.id}
        columns={columns}
        onExpand={handleExpand}
        expandable={{expandedRowRender: (record) => expandedRowRender(record), expandedRowKeys: expandedRows}}
        dataSource={data}
        pagination={false}
      />
      <FloatButton.BackTop visibilityHeight={0} />
      <ClassModal visible={visible} onFinish={onFinish} closeHandler={closeHandler} record={record} options={teacherList}/>
      <AssignModal visible={assignVisible} record={record} closeHandler={closeAssign} classStuIds={classStuIds} options={allStuList} onFinish={confirmAssign}/>
    </div>
  )
}

const mapStateToProps = ({classes}) => {
  return {
    classes,
  }
}

export default connect(mapStateToProps)(Class)
